
function openWin(name,key) {
    
    
    api.closeWin({
        name:name
    })
   
    if(key){
    	pageParam = {id: key}
    }else{
        pageParam = ''
    }
    
    api.openWin({
        name: name,
        url: name + '.html',
        opaque: true,
        vScrollBarEnabled: false,
        delay: 250,
        bounces:false,
        pageParam:pageParam,
        animation:{
	    type:"none",                //动画类型（详见动画类型常量）
	    subType:"from_right",       //动画子类型（详见动画子类型常量）
	    duration:300                //动画过渡时间，默认300毫秒
	},reload:true


    });
}
function headerstatus(){


	var systemType = api.systemType;
	var systemVersion = api.systemVersion;  // 比如： 8.0
	var version = api.version; 
	//alert(systemType);
	var h = $api.byId('header');

	if(systemType=='ios'){
		if(parseFloat(systemVersion)>=7){
			$api.prepend(h,'<div style="height: 20px;background: #FF0000"></div>');
			return true;
		}
	}/*else if(systemType=='android'){
	
		//alert(parseFloat(systemVersion))
		if(parseFloat(systemVersion)>=4.4){
			$api.prepend(h,'<div style="height: 24px;background: #FF0000"></div>');
		}
	}*/
}
function openUrl(url,title,remark){
 var url = url;

 if(url){
        pageParam = {url: url,title:title,remark:remark}
    }
	api.openWin({
        name: 'commonHeader',
        url: 'commonHeader.html',
        opaque: true,
        vScrollBarEnabled: false,
        delay: 200,
        pageParam :pageParam,
        reload:true,
        animation:{
	    type:"none",                //动画类型（详见动画类型常量）
	    subType:"from_right",       //动画子类型（详见动画子类型常量）
	    duration:300                //动画过渡时间，默认300毫秒
	},
})
}


function _openWin(name,id) {
    
     api.closeWin({
        name:name
    })
    if(id){
        pageParam = {id: id}
    }else{
        pageParam = ''
    }
    api.openWin({
        name: name,
        url: './html/'+ name + '.html',
        opaque: true,
        vScrollBarEnabled: false,
        delay: 250,
        pageParam:pageParam,
        animation:{
    type:"none",                //动画类型（详见动画类型常量）
    subType:"from_right",       //动画子类型（详见动画子类型常量）
    duration:300                //动画过渡时间，默认300毫秒
},reload:true

    });
}



function quit(){
   
    $api.rmStorage('user');
    api.execScript({
        name:'root',
        frameName: 'user',
        script: 'userReload()'
    });

    api.closeWin();


}
/*弹出一个定时自动关闭的提示框
msg:提示框内容
*/
function toast(msg){
    api.toast({
            msg: msg,
            duration: 2000,
            location: 'bottom'
            });
}
/*
返回到首页
*/
function home(){
api.execScript({
	    		name:'root',
		        script: 'exec2();'
	        });
    api.closeToWin({
            name:'root'
        });
        
     
     
}
//设置frame/window页面bounces参数
function setbounces(name,bounces){
	api.setFrameAttr({
            name: name,
            customRefreshHeader:"UIPullRefreshFlash",
            bounces:bounces
        });
}

//打开商品详情页面
function openGoodsDetail(id){
    api.closeWin({
        name:'detail'
    })
    api.openWin({
        name: 'detail',
        url: 'detail.html',
        delay:300,
        bounces:false,
        animation:{
    type:"none",                //动画类型（详见动画类型常量）
    subType:"from_right",       //动画子类型（详见动画子类型常量）
    duration:300                //动画过渡时间，默认300毫秒
},pageParam: {shopId: id},

    });
}
function _openGoodsDetail(id){
    api.closeWin({
        name:'detail'
    })
    api.openWin({
        name: 'detail',
        url: './html/detail.html',
        delay:300,
        bounces:false,
        animation:{
    type:"none",                //动画类型（详见动画类型常量）
    subType:"from_right",       //动画子类型（详见动画子类型常量）
    duration:300                //动画过渡时间，默认300毫秒
},pageParam: {shopId: id},

    });
}
//打开头部页面
function openHeader(name,id,uid){

    var pageParam;
    if(id&&uid){
         pageParam = {type: name,id: id,uid: uid}
    }else if(id){

        pageParam = {type: name,id: id}
    }else if(uid){
         pageParam = {type: name,uid: uid}
    }else{
    	pageParam = {type: name}
    }
    

        api.openWin({
        name: 'commonHeader'+name,
        url: 'commonHeader.html',
        opaque: true,
        vScrollBarEnabled: false,
        delay: 200,
        pageParam :pageParam,
        reload:true,
        animation:{
    type:"none",                //动画类型（详见动画类型常量）
    subType:"from_right",       //动画子类型（详见动画子类型常量）
    duration:300                //动画过渡时间，默认300毫秒
}

    });

}
//打开头部页面
function _openHeader(name,id,uid){

  
   

    var pageParam;
    if(id&&uid){
         pageParam = {type: name,id: id,uid: uid}
    }else if(id){

        pageParam = {type: name,id: id}
    }else if(uid){
         pageParam = {type: name,uid: uid}
    }else{
    	pageParam = {type: name}
    }
    

        api.openWin({
        name: 'commonHeader'+name,
        url: './html/'+'commonHeader.html',
        opaque: true,
        vScrollBarEnabled: false,
        delay: 200,
        pageParam :pageParam,
        reload:true,
        animation:{
    type:"none",                //动画类型（详见动画类型常量）
    subType:"from_right",       //动画子类型（详见动画子类型常量）
    duration:300                //动画过渡时间，默认300毫秒
}

    });

}
function openH(){

	api.closeWin()
	_openFrame(3)
	
}


function classifyOpenWin(name,type) {

    api.openWin({
        name: name,
        url: name + '.html',
        opaque: true,
        vScrollBarEnabled: false,
        delay: 200,
        pageParam: {
        type: type
    },
    reload:true,
    animation:{
    type:"none",                //动画类型（详见动画类型常量）
    subType:"from_right",       //动画子类型（详见动画子类型常量）
    duration:300                //动画过渡时间，默认300毫秒
}

    });
    
}

//user
function delWord(el) {
    var input = $api.prev(el, '.txt');
    input.value = '';
}
function edit(el) {
    var del = $api.next(el, '.del');
    if (el.value) {
        $api.addCls(del, 'show');
    }
    $api.addCls(el, 'light');
}
function cancel(el) {
    var del = $api.next(el, '.del');
    $api.removeCls(del, 'show');
    $api.removeCls(el, 'light');
}

function addData(data, str) {
    if (!data) {
        data = str;
    } else {
        if (data.indexOf(str) > -1) {
            return;
        } else {
            data = data + ',' + str;
        }
    }

    return data;
}





/**
 * Created by Administrator on 2014/12/17.
 */
/**
 *
 *  Secure Hash Algorithm (SHA1)
 *  http://www.webtoolkit.info/
 *
 **/

function SHA1(msg) {

    function rotate_left(n, s) {
        var t4 = ( n << s ) | (n >>> (32 - s));
        return t4;
    };

    function lsb_hex(val) {
        var str = "";
        var i;
        var vh;
        var vl;

        for (i = 0; i <= 6; i += 2) {
            vh = (val >>> (i * 4 + 4)) & 0x0f;
            vl = (val >>> (i * 4)) & 0x0f;
            str += vh.toString(16) + vl.toString(16);
        }
        return str;
    };

    function cvt_hex(val) {
        var str = "";
        var i;
        var v;

        for (i = 7; i >= 0; i--) {
            v = (val >>> (i * 4)) & 0x0f;
            str += v.toString(16);
        }
        return str;
    };


    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    msg = Utf8Encode(msg);

    var msg_len = msg.length;

    var word_array = new Array();
    for (i = 0; i < msg_len - 3; i += 4) {
        j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
            msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
        word_array.push(j);
    }

    switch (msg_len % 4) {
        case 0:
            i = 0x080000000;
            break;
        case 1:
            i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
            break;

        case 2:
            i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
            break;

        case 3:
            i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
            break;
    }

    word_array.push(i);

    while ((word_array.length % 16) != 14) word_array.push(0);

    word_array.push(msg_len >>> 29);
    word_array.push((msg_len << 3) & 0x0ffffffff);


    for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {

        for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i];
        for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for (i = 0; i <= 19; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 20; i <= 39; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 40; i <= 59; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 60; i <= 79; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;

    }

    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

    return temp.toLowerCase();

}


//显示加载框
function showProgress(){
    api.showProgress({
        title: '加载中...',
        modal: false
    });
}
//设置frame组当前可见frame
 function _openFrame(index,name) {

    
        try {
       //alert(11111)

            api.setFrameGroupIndex({
                name: 'group',
                index: index,
                scroll: false,
                reload: true
            });
        } catch (e) {
            alert(e)
        }

    }
    

    function openFrame(index,name) {

    
        try {
       //alert(11111)

            api.setFrameGroupIndex({
                name: 'group',
                index: index,
                scroll: false,
                
            });
        } catch (e) {
            alert(e)
        }

    }
    function openFrame3(index,name) {

    
        try {
       //alert(11111)

            api.setFrameGroupIndex({
                name: name,
                index: index,
                scroll: false,
                
            });
        } catch (e) {
            alert(e)
        }

    }
    
//头部历史返回
    function back(){
        api.historyBack({
   
        },function(ret,err){
            if(!ret.status){
            api.closeWin();
        }
    });
 }
 function isImg(str)
{
    var objReg = new RegExp("[.]+(jpg|jpeg|swf|gif|png)$", "gi");
    if(objReg.test(str))
    {
        return true;
    }
    return false;
}
function isPng(str)
{
    var objReg = new RegExp("[.]+(png)$", "gi");
    if(objReg.test(str))
    {
        return true;
    }
    return false;
}
//获取user登录信息
function getStorage(){
    var user = $api.getStorage('user');
    if(user&&user!=''){
        return user;
    }else{
        return false;
    }
}
//下拉刷新
function Refresh_one(){
     api.setCustomRefreshHeaderInfo({
            bgColor : '#f0f0f0',
            image: {
        pull: 'widget://image/refresh/1.png', 
        transform: [
            'widget://image/refresh/1.png', 
            'widget://image/refresh/2.png',
            'widget://image/refresh/3.png',
            'widget://image/refresh/4.png',
            'widget://image/refresh/5.png',
            'widget://image/refresh/6.png',
            'widget://image/refresh/7.png'
        ],
        load: [ 
            'widget://image/refresh/1.png', 
            'widget://image/refresh/2.png',
            'widget://image/refresh/3.png', 
            'widget://image/refresh/4.png',
            'widget://image/refresh/5.png'
        ]
    }
        }, function() {
            //下拉刷新被触发，自动进入加载状态，使用 api.refreshHeaderLoadDone() 手动结束加载中状态
            setTimeout(function(){
                 var typeName = $api.getStorage('type');
        getBanner();
        getWinInfo();
        //alert(typeName)
        getData(typeName,true);
        $api.rmStorage('type');
        $api.setStorage('type',typeName);
        showNav(typeName);
        api.refreshHeaderLoadDone();
            }, 800);
           
        });
}

//添加购物车
function addCart(id,buy){
if(!buy){
if($api.getStorage("cartNum")>=10){
    	toast("最多只能添加10个商品");
    	return;
    }
toast('添加成功')
}
	if(id==''){
	var re = true;
	}else{
	var re = false;
	}

api.sendEvent({
    name: 'addCart',
    extra: {
        refresh: re, 
        id: ''+id
    }
});
if(buy){
    setTimeout(backCart,300)
    }

   /* api.closeFrame({
        name:'cart'
    })
   
     api.execScript({
        name:'root',
        frameName: 'cart',
        script: 'getCart(false,'+id+')'
    });
    if(buy){
    setTimeout(backCart,300)
    }*/
   
     
}
function t(){
 api.closeWin({
           });

}
function backCart(){
api.execScript({
	    		name:'root',
		        script: 'exec();'
	        });
            setTimeout(t,300)
	
	       
	        api.closeToWin({
	        	name:'root'
	        })
}

function backmain(){
	api.execScript({
	    		name:'root',
		        script: 'exec2();'
	        });
	        
}

 function dialogBox_alert1() {
  var dialogBox = api.require('dialogBox');
    dialogBox.alert({
        texts : {
            title : ' 确认',
            content : '您是游客状态，是否登录？',
            leftBtnTitle : '取消',
            rightBtnTitle : '登录'
        },
        styles : {
            bg : '#fff',
            corner : 6,
            w : 260,
            title : {
                marginT : 20,
                icon : 'widget://image/gou.png',
                iconSize : 32,
                titleSize : 18,
                titleColor : '#000'
            },
            content : {
                color : '#000',
                size : 16
            },
            left : {
                marginB : 15,
                marginL : 40,
                w : 40,
                h : 35,
                corner : 2,
                color : "#000",
                bg : '#fff',
                size : 16
            },
            right : {
                marginB : 15,
                marginL : 88,
                w : 40,
                h : 35,
                corner : 2,
                color : "#000",
                bg : '#fff',
                size : 16
            }
        },
        tapClose : true
    }, function(ret) {
        if (ret.eventType == 'left') {
            dialogBox.close({
                dialogName: 'alert'
            });
        }else{
	        dialogBox.close({
	                dialogName: 'alert'
	            });
	        	openFrame(4)
        }
    });
}

/*connection none 
 	无网络 网络断开页面
 */
function noneConnection(){
	var connection = api.connectionType;
	if(connection=='none'){
		//
	}
}
function error(){

	var html = '<div style=" text-align: center;background:#fff"><div style="padding-top: 45%;"><img src="../image/networkerror.png" width="120px" height="120px"></div><div style="margin: 10px 0px"><p class="gray">网络连接异常~</p></div><div  style="margin-bottom: 32px;background-color: #fff"><div style="text-align: center; margin-top: 10px"><a id="reloading" href="javascript:;" style="    width: 110px;background: #FF0000;border: 1px solid #FF0000;  display: inline-block;color: #fff;height: 32px;line-height: 32px;text-align: center;font-size: 16px;border-radius: 4px;">重新加载</a></div></div></div>';
	$api.html($api.byId('app'),html);
}
/*man版本更新*/
	function checkUpdate() {
            var mam = api.require('mam');
            mam.checkUpdate(function(ret, err) {
                if (ret) {
                    var result = ret.result;
                    if (result.update == true & result.closed == false) {
                        var str = '新版本型号:' + result.version + ';更新提示语:' + result.updateTip + ';下载地址:' + result.source + ';发布时间:' + result.time;
                        api.confirm({
                            title : '新版本更新 ',
                            msg : result.updateTip,
                            buttons : ['确定', '取消']
                        }, function(ret, err) {
                            if (ret.buttonIndex == 1) {
                                if (api.systemType == "android") {
                                    api.download({
                                        url : result.source,
                                        report : true
                                    }, function(ret, err) {
                                        if (ret && 0 == ret.state) {/* 下载进度 */
                                            /*api.toast({
                                                msg : "正在下载应用" + ret.percent + "%",
                                                duration : 2000
                                            });*/
                                        }
                                        if (ret && 1 == ret.state) {/* 下载完成 */
                                            var savePath = ret.savePath;
                                            api.installApp({
                                                appUri : savePath
                                            });
                                        }
                                    });
                                }
                                if (api.systemType == "ios") {
                                    api.installApp({
                                        appUri : result.source
                                    });
                                }
                            }
                        });
                    } else {
                       /* api.alert({
                            msg : "暂无更新"
                        });*/
                    }
                } else {
                    api.alert({
                        msg : err.msg
                    });
                }
            });
        }
         /*版本更新结束*/
        
        
//      function unregisterPush(){
//      	 // 注册设备并绑定用户账号
//			var tencentPush = api.require('tencentPush');
//			// 反注册设备
//			
//			var resultCallback = function(ret, err) {
//			    if (ret.status) {
//			        alert("反注册成功，token：" + ret.token);
//			    } else {
//			        alert("反注册失败，错误码：" + err.code + "，错误信息：" + err.msg);
//			    }
//			};
//			tencentPush.unregisterPush(resultCallback);
//      }
